package com.value.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class ProThread extends Thread {
	private Socket socket;
	private InputStream in = null;
	public static final String WEB_ROOT = "E:\\WorkSpace\\mockApache\\src\\hdocs";

	public ProThread(Socket socket) {
		this.socket = socket;
		try {
			this.in = socket.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		String name = parse();
		if (name == null || "".equals(name)) {
			sendErrorMessage(404, "文件未找到！！");
			return;
		}
		sendFile(name);
	}

	private String parse() {
		String fileName = null;
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String[] content = br.readLine().split(" ");

			if (content == null) {
				sendErrorMessage(400, "request Error！！！");
				return fileName;
			}
			System.out
					.println(content[0] + "," + content[1] + "," + content[2]);
			if (content.length != 3) {
				sendErrorMessage(400, "request Error！！！");
				return fileName;
			}
			fileName = content[1];

		} catch (IOException e) {
			sendErrorMessage(500, "Service Error:" + e.getMessage());
		} 
		return fileName;
	}

	private void sendErrorMessage(int errorCode, String message) {
		PrintStream out = null;
		try {
			out = new PrintStream(this.socket.getOutputStream());
			out.println("HTTP/1.1 " + errorCode + " Error");
			out.println("content-type:text/html");
			out.println();
			out.println("<html>");
			out.println("<title>");
			out.println("Error Message</title>");
			out.println("<body>");
			out.println("<h1>ErrorCode:" + errorCode + "</h1>");
			out.println("<h3>ErrorMessage:" + message + "</h3>");
			out.println("</body>");
			out.println("</html>");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void sendFile(String fileName) {
		File file = new File(WEB_ROOT + fileName);
		if (!file.exists()) {
			sendErrorMessage(404, "file not exists..");
			return;
		}
		InputStream fileIn = null;
		PrintStream out = null;
		try {
			out = new PrintStream(this.socket.getOutputStream());
			fileIn = new FileInputStream(file);
			byte[] content = new byte[(int) file.length()];
			fileIn.read(content);
			out.println("HTTP/1.1 200 OK");
			out.println("content-length:" + content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			fileIn.close();
			System.out.println("response file " + file.getName()
					+ " and filelength:" + content.length);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
